package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.hosp.globalexp.YyghException;
import com.atguigu.yygh.hosp.result.R;
import com.atguigu.yygh.hosp.util.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

//@RestController
@Controller
@RequestMapping("/api/user/wx")
public class WeixinController {

    @Value("${wx.open.app_id}")
    String appId;
    @Value("${wx.open.redirect_url}")
    String url;
    @Value("${wx.open.app_secret}")
    String secret;
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    UserInfoService userInfoService;

    //url?code=xxx
    @GetMapping("/callback")
    public String callback(String code) throws UnsupportedEncodingException {
        //根据code获取accessToken(根据临时票据code获取真实票据accessToken)进而获取用户的信息用户名openid...
        String url1="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        String object1 = restTemplate.getForObject(url1, String.class);
        Map map1 = JSON.parseObject(object1, Map.class);
        String access_token = String.valueOf(map1.get("access_token"));
        String openid = String.valueOf(map1.get("openid"));

//        String url2="https://api.weixin.qq.com/sns/auth?access_token="+access_token+"&openid="+openid;
        String url2 = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid;
        String object2 = restTemplate.getForObject(url2, String.class);
        Map map2 = JSON.parseObject(object2, Map.class);
        String nickname = String.valueOf(map2.get("nickname"));
        System.out.println(nickname);

//---------------------------------------需求---------------------------------------------

      UserInfo userInfo = userInfoService.selectUserByOpenid(openid);
      if(userInfo==null){
          //微信用户不存在,自动注册
          userInfo=new UserInfo();
          userInfo.setOpenid(openid);
          userInfo.setNickName(nickname);
          userInfo.setAuthStatus(AuthStatusEnum.NO_AUTH.getStatus());  //0未认证
          userInfo.setStatus(1); //1正常状态
          boolean save = userInfoService.save(userInfo);
          if(!save){
              throw new YyghException(20001,"该微信用户注册失败");
          }
      }
      //判断用户的状态是否可用
      if(userInfo.getStatus()==0){
          throw new YyghException(20001,"该用户已被锁定,禁止登录");
      }

      //重定向到前端的某个页面
      String name = userInfo.getName();
      if(StringUtils.isEmpty(name)){
          name=userInfo.getNickName();
          if(StringUtils.isEmpty(name)){
              name=userInfo.getPhone();
          }
      }
      String token = JwtHelper.createToken(userInfo.getId(), name);
      //登录成功之后,右上角name的值如果乱码,就是重定向时出现的问题
      //重定向过程中,中文乱码,也就是URl中的乱码就使用URLEncoder
       name = URLEncoder.encode(name,"utf-8");

      if(StringUtils.isEmpty(userInfo.getPhone())){
          return "redirect:http://localhost:3000/weixin/callback?name="+name+"&token="+token+"&openid="+openid;
      }else {
          return "redirect:http://localhost:3000/weixin/callback?name=" + name + "&token=" + token + "&openid=" + "";
      }
    }


    /**
     * 获取二维码所需要的必要参数
     */
    @ResponseBody
    @GetMapping("/getLoginParam")
    public R getLoginParam() throws Exception{


        Map map=new HashMap<>();
        map.put("self_redirect",true); //弹出框(小窗口)重定向到redirect_uri
        map.put("id","weixinLogin"); //二维码显示在哪个控件中
        map.put("appid",appId); //应用唯一标识，在微信开放平台提交应用审核通过后获得
        map.put("scope","snsapi_login"); //应用授权作用域，拥有多个作用域用逗号（,）分隔，网页应用目前仅填写snsapi_login即可
        map.put("redirect_uri",URLEncoder.encode(url,"utf-8"));//重定向地址，需要进行UrlEncode
        //扫码后,手机端点击允许(确认),自动重定向调用的哪个接口

        return R.ok().data(map);
    }



}
